package com.newshub.app.ui.favorite

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.launch

class FavoriteViewModel : ViewModel() {
    
    private val repository = NewsRepository

    private val _favoriteNews = MutableLiveData<List<News>>()
    val favoriteNews: LiveData<List<News>> = _favoriteNews
    
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _errorMessage = MutableLiveData<String?>(null)
    val errorMessage: LiveData<String?> = _errorMessage
    
    fun loadFavoriteNews() {
        viewModelScope.launch {
            _isLoading.value = true
            _errorMessage.value = null
                    try {
                        // 直接获取收藏的新闻，避免RxJava订阅问题
                        val newsList = repository.getFavoriteNews().blockingFirst()
                        _favoriteNews.value = newsList
                        _isLoading.value = false
            } catch (e: Exception) {
                _errorMessage.value = "加载收藏失败: ${e.message}"
                _favoriteNews.value = emptyList()
                _isLoading.value = false
            }
        }
    }
    
    fun toggleFavorite(news: News) {
        viewModelScope.launch {
            try {
                if (news.isFavorite) {
                    repository.removeFromFavorite(news.docid)
                } else {
                    repository.addToFavorite(news)
                }
                
                // 重新加载收藏列表以更新UI
                loadFavoriteNews()
            } catch (e: Exception) {
                _errorMessage.value = "更新收藏状态失败"
            }
        }
    }
}